package com.example.springboot.service;

import com.example.springboot.entity.Device;
import com.example.springboot.entity.SelfServicePoint;
import com.example.springboot.mapper.SelfServicePointMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.springboot.mapper.DeviceMapper;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 获取设备状态
     * @param deviceId 设备ID
     * @return Device 实体
     */
    public Device getDeviceStatus(Integer deviceId) {
        Device device = deviceMapper.getDeviceById(deviceId);
        if (device == null) {
            throw new IllegalArgumentException("设备不存在，ID：" + deviceId);
        }
        return device;
    }

    /**
     * 根据 point_id 获取设备列表
     * @param pointId 设备点ID
     * @return 设备列表
     */
    public List<Device> getDevicesByPoint(Integer pointId) {
        List<Device> devices = deviceMapper.getDevicesByPoint(pointId);
        if (devices == null || devices.isEmpty()) {
            throw new IllegalArgumentException("没有找到设备，point_id：" + pointId);
        }
        return devices;
    }

    /**
     * 更新设备状态
     * @param deviceId 设备ID
     * @param newStatus 新状态
     */
    public void updateDeviceStatus(Integer deviceId, String newStatus) {
        Device device = deviceMapper.getDeviceById(deviceId);
        if (device != null) {
            device.setStatus(newStatus);
            deviceMapper.updatestatus(device);
        }
    }


    public Integer getPointIdByDeviceId(Integer deviceId) {
        return deviceMapper.getPointIdByDeviceId(deviceId);
    }
    @Autowired
    private SelfServicePointMapper selfServicePointMapper;
    private static final Logger logger = LoggerFactory.getLogger(DeviceService.class);

    // 获取设备列表（根据管理员角色过滤）
    public List<Device> getAllDevices(String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        try {
            logger.info("Fetching all devices for role: {}, username: {}", role, decodedUsername);
            if ("super".equals(role)) {
                logger.info("Super admin access: retrieving all devices");
                List<Device> devices = deviceMapper.findAll();
                logger.info("Retrieved {} devices", devices.size());
                return devices;
            } else {
                logger.info("Non-super role access: retrieving devices by admin ID");
                Integer adminId = getAdminId(decodedUsername);
                List<Device> devices = deviceMapper.findByAdminId(adminId);
                logger.info("Retrieved {} devices for adminId: {}", devices.size(), adminId);
                return devices;
            }
        } catch (Exception e) {
            logger.error("Failed to fetch devices for role: {}, username: {}", role, decodedUsername, e);
            throw new RuntimeException("获取设备列表失败: " + e.getMessage(), e);
        }
    }

    public Device getDeviceById(Integer deviceId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        Device device = deviceMapper.findById(deviceId);
        if (device == null) {
            logger.warn("Device not found for deviceId: {}", deviceId);
            throw new IllegalArgumentException("设备不存在");
        }

        try {
            if ("ADMIN".equals(role) && !"super".equals(role)) {
                String adminRole = selfServicePointMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("common".equals(adminRole)) {
                    Integer adminId = getAdminId(decodedUsername);
                    SelfServicePoint point = selfServicePointMapper.findById(device.getPointId());
                    if (point == null || !point.getAdminId().equals(adminId)) {
                        logger.warn("Permission denied for username: {} to view deviceId: {}", decodedUsername, deviceId);
                        throw new IllegalArgumentException("无权限查看该设备");
                    }
                }
            }
            logger.info("Successfully fetched device {} for username: {}", deviceId, decodedUsername);
            return device;
        } catch (Exception e) {
            logger.error("Failed to fetch device {} for role: {}, username: {}", deviceId, role, decodedUsername, e);
            throw new RuntimeException("获取设备信息失败: " + e.getMessage(), e);
        }
    }

    public Device addDevice(Device device, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        SelfServicePoint point = selfServicePointMapper.findById(device.getPointId());
        if (point == null) {
            logger.error("Self-service point not found for pointId: {}", device.getPointId());
            throw new IllegalArgumentException("指定的自助点不存在");
        }

        try {
            if ("ADMIN".equals(role) && !"super".equals(role)) {
                String adminRole = selfServicePointMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("common".equals(adminRole)) {
                    Integer adminId = getAdminId(decodedUsername);
                    if (!point.getAdminId().equals(adminId)) {
                        logger.warn("Permission denied for username: {} to add device to pointId: {}", decodedUsername, point.getPointId());
                        throw new IllegalArgumentException("无权限向该自助点添加设备");
                    }
                }
            }

            device.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
            deviceMapper.insert(device);
            logger.info("Successfully created device for username: {}, pointId: {}", decodedUsername, device.getPointId());
            return device;
        } catch (Exception e) {
            logger.error("Failed to create device for role: {}, username: {}, pointId: {}", role, decodedUsername, device.getPointId(), e);
            throw new RuntimeException("创建设备失败: " + e.getMessage(), e);
        }
    }

    public Device updateDevice(Integer deviceId, Device device, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        Device existingDevice = deviceMapper.findById(deviceId);
        if (existingDevice == null) {
            logger.warn("Device not found for deviceId: {}", deviceId);
            throw new IllegalArgumentException("设备不存在");
        }

        SelfServicePoint point = selfServicePointMapper.findById(device.getPointId());
        if (point == null) {
            logger.error("Self-service point not found for pointId: {}", device.getPointId());
            throw new IllegalArgumentException("指定的自助点不存在");
        }

        try {
            if ("ADMIN".equals(role) && !"super".equals(role)) {
                String adminRole = selfServicePointMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("common".equals(adminRole)) {
                    Integer adminId = getAdminId(decodedUsername);
                    if (!point.getAdminId().equals(adminId)) {
                        logger.warn("Permission denied for username: {} to update deviceId: {}", decodedUsername, deviceId);
                        throw new IllegalArgumentException("无权限操作该设备");
                    }
                }
            }

            device.setDeviceId(deviceId);
            deviceMapper.update(device);
            logger.info("Successfully updated device {} for username: {}", deviceId, decodedUsername);
            return device;
        } catch (Exception e) {
            logger.error("Failed to update device {} for role: {}, username: {}", deviceId, role, decodedUsername, e);
            throw new RuntimeException("更新设备失败: " + e.getMessage(), e);
        }
    }

    public void deleteDevice(Integer deviceId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        Device device = deviceMapper.findById(deviceId);
        if (device == null) {
            logger.warn("Device not found for deviceId: {}", deviceId);
            throw new IllegalArgumentException("设备不存在");
        }

        try {
            if ("ADMIN".equals(role) && !"super".equals(role)) {
                String adminRole = selfServicePointMapper.findAdminRoleByUsername(decodedUsername);
                if (adminRole == null) {
                    logger.error("No role found for username: {}", decodedUsername);
                    throw new IllegalArgumentException("管理员用户不存在或角色未定义");
                }
                if ("common".equals(adminRole)) {
                    Integer adminId = getAdminId(decodedUsername);
                    SelfServicePoint point = selfServicePointMapper.findById(device.getPointId());
                    if (point == null || !point.getAdminId().equals(adminId)) {
                        logger.warn("Permission denied for username: {} to delete deviceId: {}", decodedUsername, deviceId);
                        throw new IllegalArgumentException("无权限删除该设备");
                    }
                }
            }

            deviceMapper.deleteById(deviceId);
            logger.info("Successfully deleted device {} for username: {}", deviceId, decodedUsername);
        } catch (Exception e) {
            logger.error("Failed to delete device {} for role: {}, username: {}", deviceId, role, decodedUsername, e);
            throw new RuntimeException("删除设备失败: " + e.getMessage(), e);
        }
    }

    private void validateInput(String role, String username) {
        if (username == null || username.trim().isEmpty()) {
            logger.error("Username is null or empty");
            throw new IllegalArgumentException("Username header is required");
        }
        if (role == null || role.trim().isEmpty()) {
            logger.error("Role is null or empty");
            throw new IllegalArgumentException("Role header is required");
        }
    }

    private Integer getAdminId(String username) {
        Integer adminId = selfServicePointMapper.findAdminIdByUsername(username);
        if (adminId == null) {
            logger.error("No admin ID found for username: {}", username);
            throw new IllegalArgumentException("无法获取管理员 ID，用户名可能不存在");
        }
        return adminId;
    }

    private String decodeUsername(String username) {
        if (username == null) {
            return null;
        }
        try {
            return URLDecoder.decode(username, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            logger.warn("Failed to decode username: {}, using original value", username, e);
            return username;
        }
    }
}
